package com.aduerr.v1shouyin.http;

import android.content.Context;
import android.util.Log;
import com.aduerr.v1shouyin.App;
import com.aduerr.v1shouyin.util.MD5Util;
import com.aduerr.v1shouyin.util.Versionutil;
import com.orhanobut.hawk.Hawk;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 类名: RXRequest
 * 此类用途: ---
 *
 * @Date: 2017-08-10 15:22
 * @FileName: com.aduer.shouyin.http.RXRequest.java
 */
public class RXRequest {
    private final static String si = "8250225678eb1d1220e939cc0dedfc9c94bbcdf2";
    private static Map<String, String> params = new ConcurrentHashMap<>();

//    public static Map<String, String> getParams(Map<String, String> addParams,
//    Context context) {
//        mcontext = context;
//        try {
//            params = new ConcurrentHashMap<>();
//            for (Map.Entry<String, String> en : params.entrySet()) {
//                if (en.getValue() == null || en.getValue().length() <= 0)//去除map空值value
//                    params.remove(en.getKey());
//            }
//            params.remove("opid");//历史遗留问题，需要特殊处理
//            params.remove("opass");
//            params.put("deviceID", Installation.deviceId(context));
//            params.put("timeStamp", ((int) (System.currentTimeMillis() / 1000)) + "");
//            params.put("opId", (String) Hawk.get(Constants.OPID));
//            params.put("password", (String) Hawk.get(Constants.PASSWORD));
//            params.putAll(addParams);
//            if (params.containsKey("sign")) {
//                params.remove("sign");
//            }
//            String sign = getSign(params);
//            params.put("sign", sign);
//            Log.i("sage===str", "params===" + params);
//        } catch (Exception e) {
//            e.printStackTrace();
//            Log.e("ERRO", e.toString());
//        }
//        return params;
//    }

    /**
     * 获取签名
     **/
    public static String getSign(Map<String, String> mMap) {
        List<Integer> intP = new ArrayList<Integer>();
        intP.add(1);
        intP.add(10);
        intP.add(3);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        Set<String> set = mMap.keySet();
        Iterator<String> it = set.iterator();
        while(it.hasNext()) {
            String key = it.next();
            params.add(new BasicNameValuePair(key, mMap.get(key)));

        }
        Collections.sort(intP, new Comparator<Integer>() {
            public int compare(Integer arg0, Integer arg1) {
                return arg1.compareTo(arg0);
            }
        });
        Collections.sort(params, new Comparator<NameValuePair>() {
            public int compare(NameValuePair arg0, NameValuePair arg1) {
                String name0 = arg0.getName();
                String name1 = arg1.getName();
                return name0.compareToIgnoreCase(name1);
            }
        });
        StringBuilder builder = new StringBuilder();
        for(NameValuePair item : params) {
            builder.append(item.getValue());
        }
        builder.append(si);
        String str = builder.toString().toLowerCase();

        try {
            //全部变小写
            str = URLEncoder.encode(str, "UTF-8").toLowerCase();
        } catch(UnsupportedEncodingException pE) {
            pE.printStackTrace();
        }
        Log.i("sage===str", "str--- " + str);

        String sign = MD5Util.MD5(str);
        Log.i("sage===str", "sign===" + sign);

        return sign;
    }

    public static Map<String, String> getXingPosParams(Map<String, String> addParams,
                                                       Context context) {
        try {
            params = new ConcurrentHashMap<>();
            for(Map.Entry<String, String> en : params.entrySet()) {
                if(en.getValue() == null || en.getValue().length() <= 0)//去除map空值value
                    params.remove(en.getKey());
            }
            params.put("deviceid", Hawk.get("DeviceID"));
            //如果是登录和获取激活码的就不添加这几个参数了,登录后其他的接口全部添加这4个必要的 的参数opId,oPass,deviceid,sign
            if(!addParams.containsKey("logType") && !addParams.containsKey("sncode")) {
                addParams.put("opid", Hawk.get("opId"));
                addParams.put("opass", Hawk.get("oPass"));
            }
            params.putAll(addParams);
            if(params.containsKey("sign")) {
                params.remove("sign");
            }

            params.put("timeStamp", ((int) (System.currentTimeMillis() / 1000)) + "");
            params.put("random", ((Math.random() * 100) + 1) + "");
            //新增版本号
            params.put("version", Versionutil.getVersionName(App.getApp()));

            String sign = getXingPosSign(params);
            params.put("sign", sign);
            Log.i("sage===str", "params===" + params);
        } catch(Exception e) {
            e.printStackTrace();
            Log.e("ERRO", e.toString());
        }
        return params;
    }


    /**
     * 得到星pos的签名
     **/
    public static String getXingPosSign(Map<String, String> mMap) {

//        List<Integer> intP = new ArrayList<Integer>();
//        intP.add(1);
//        intP.add(10);
//        intP.add(3);
//        Collections.sort(intP, new Comparator<Integer>() {
//            public int compare(Integer arg0, Integer arg1) {
//                return arg1.compareTo(arg0);
//            }
//        });

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        Set<String> set = mMap.keySet();
        Iterator<String> it = set.iterator();
        while(it.hasNext()) {
            String key = it.next();
            params.add(new BasicNameValuePair(key, mMap.get(key)));
        }

        Collections.sort(params, new Comparator<NameValuePair>() {
            public int compare(NameValuePair arg0, NameValuePair arg1) {
                String name0 = arg0.getName();
                String name1 = arg1.getName();
                return name0.compareToIgnoreCase(name1);
            }
        });
        StringBuilder stringBuilder = new StringBuilder();
        StringBuilder builder = new StringBuilder();
        for(NameValuePair item : params) {
            builder.append(item.getValue());
            System.out.println(item.getName() + ":" + item.getValue());
            stringBuilder.append(item.getName() + "=" + item.getValue() + "&");
        }
        builder.append("_aduer");
        String str = builder.toString().toLowerCase();
        Log.e("sagexing", "签名之前===" + str);
        String sign = MD5Util.MD5(str);
        Log.e("sagexing", "签名之后===" + sign);

        stringBuilder.append("sign=" + sign);
        Log.i("sage===str request", stringBuilder.toString());
        return sign;
    }


    public RXRequest add(String key, String value) {
        params.put(key, value);
        return this;
    }

    public RXRequest addll(Map<String, String> params) {
        this.params.putAll(params);
        return this;
    }


}
